const addonPackage = (() => {
  let jsPath = '';
  const doc = document;
  if (doc.currentScript) {
    jsPath = doc.currentScript.src;
  } else {
    const js = doc.scrollingElement;
    const last = js.length - 1;
    for (let i=last;i>0;i--) {
      if (js[i].readyState === 'interactive') {
        jsPath = js[i].src;
        break;
      }
    }
    if (!jsPath) {
      jsPath = js[last].src;
    }
  }

  const matches = jsPath.match(/\/_addons\/([^/]+)\/web\/my-addon.js/)

  return matches ? matches[1] : null
})();

const editorCss = `/_addons/${addonPackage}/web/editor.css`;

const myaddonRefreshEditor = () => {
  setTimeout(() => {
    Array.prototype.forEach.call(
      document.querySelectorAll('.rich-text-editable'),
      (el) => {
        if (!el.classList.contains('myaddon')) {
          const sr = el.shadowRoot;
          const style = document.createElement('link');
          style.setAttribute('rel', 'stylesheet');
          style.setAttribute('href', editorCss);
          sr.appendChild(style);
          el.classList.add('myaddon');
        }
      }
    );
  }, 167);
};